<?php

class User_Action_Connect
{
	function execute($request)
	{
		$socialuser = null;

		$form = Form::factory('user/connect');

		if ($request -> getParam('idp'))
		{
			$socialuserid = $request -> getParam('idp');

			$socialuser = Document::factory('socialuser', $socialuserid);

			if ($socialuser -> load())
			{
				$form -> setData($socialuser -> as_array());

				if ($socialuser -> user_id)
				{
					$user = Document::factory('user', intval($socialuser -> user_id));

					// user exsits && mapped, so please
					if ($user -> load())
					{
						$user -> login();
						Agilet::redirect('/');
					}
				}

				if ($socialuser -> email)
				{

					$user = Document::factory('user') -> collection() -> findOne(array('email' => $socialuser -> email));

					if ($user)
					{
						$request -> response = View::render($script = 'user/html/connect', array());
						return;
					}
				}
			}
		}

		if ($socialuser)
		{
			if ($socialuser -> email != null)
			{
				$form -> removeChild('email');
			}

			if ($socialuser -> name != null)
			{
				$form -> removeChild('name');
			}

			$data = $socialuser -> as_array();

			$form -> setDesc(View::render($script = 'form/user/connect/desc', $data));

		}

		if ($request -> isPost() && $form -> isValid($_POST))
		{
			$data = $form -> getData();

			$user = Document::factory('user');
			$user -> _id = $user -> collection() -> getAutoID();
			$user -> name = $socialuser -> name;
			$user -> email = $socialuser -> email;
			$user -> gender = $socialuser -> gender;
			$user -> birthday = $socialuser -> birthday;
			$user -> setPassword($data['password']);
			$user -> created_at = time();
			$user -> updated_at = time();
			$user -> created_ip = $request -> getClientIp();
			$user -> login_ip = $request -> getClientIp();
			$user -> save(true);

			$socialuser -> user_id = $user -> _id;

			$socialuser -> save(true);

			$user -> login();

			Agilet::redirect('/');

		}

		$request -> response = View::render($script = 'user/html/connect', array('form' => $form));
	}

}
